//字符串转Buffer。node.js里可直接使用：Buffer.from("string", "utf8")
function str2ab(str) {
    var buf = new ArrayBuffer(str.length * 2); //每个字符占用2个字节
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}
//Buffer转字符
function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function buf2hex(buffer, space) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(space);
}

function hex2buf(key, space) {
    key = '0x' + (key).replace(new RegExp(space, 'g'), ',0x');
    return new Uint8Array(key.split(",")).buffer;
}